<?php
namespace Usap\Service\Account;

use Usap\Service\Service;
class device{
	

	
	/**
	 * 添加wifi设备
	 * @param string $station_no
	 * @param string $mobile
	 * @param string $mac_address
	 * @param string $province
	 * @param string $city
	 * @param string $district
	 * @param string $streent_name
	 * @param string $run_status
	 * @return multitype:string
	 */
	public function addDevice($gw_id, $mac_address, $province, $city, $district, $street_name, $run_status, $station_no='', $mobile='',$protal_page='', $login_page=''){

		
		if(empty($province)){
			
			return array('code'=>'PROVINCE_NULL','msg'=>'请选择省份');
		}
		if(empty($city)){
			
			return array('code'=>'CITY_NULL','msg'=>'请选择城市');
		}
		if(empty($district)){
			
			return array('code'=>'DISTRICT_NULL','msg'=>'请选择区域');
		}
		if(empty($street_name)){

			return array('code'=>'STREET_NULL','msg'=>'街道信息不能为空');
		}
		
		if(!empty($mobile) && !preg_match('/^1[0-9]{10}$/', $mobile)){
			
			return array('code'=>'MOBILE_ERROR','msg'=>'店主联系方式必须为11位数字');
		}
		if(!empty($mac_address) && !preg_match('/^[0-9A-F]{12}$/i', $mac_address)){
			
			return array('code'=>'MACADDRESS_ERROR','msg'=>'您当前填写的网卡地址必须为12位字母与数字的混合串');
		}
		
		
		
		$protal_page = $protal_page ? $protal_page : C('portal_page');
		$login_page = $login_page ? $login_page : C('login_page');

		$device_info = array(
			'gw_id'=>$gw_id,'name'=>$gw_id,'mac_address'=>$mac_address,
			'province'=>$province,'city'=>$city,'country'=>$district,'street_name'=>$street_name,
			'station_no'=>$station_no,
			'public_phone_number'=>$mobile,
			'portal_page'=>$protal_page,//认证地址
			'login_page'=>$login_page,//认证成功后跳转地址
			'created_at'=>date('Y-m-d H:i:s'),
			'updated_at'=>date('Y-m-d H:i:s'),
		);
		
		$deployment_status = 'TEMPORARILY_CLOSED';
		if($run_status=='Run'){

			$deployment_status = 'DEPLOYED';
		}
		$device_info['deployment_status'] = $deployment_status;
		
		
		if(!empty($device_info['mac_address'])){//MAC地址唯一
				
			$exists_no = D("Usap/Authpuppy/Nodes")->where("mac_address='".$device_info['mac_address']."'")->count();
			if($exists_no){
		
				return array('code'=>'-1004','msg'=>'相同MAC地址的设备之前已存在，请重试');
			}
		}
		
		if(!empty($device_info['station_no'])){//站点编号唯一
				
			$exists_no = D("Usap/Authpuppy/Nodes")->where("station_no='".$device_info['station_no']."'")->count();
			if($exists_no){
					
				return array('code'=>'-1005','msg'=>'相同站点编号的设备之前已存在，请重试');
			}
		}
		
		$add_result = D("Usap/Authpuppy/Nodes")->add($device_info);
		if($add_result){

			return array('code'=>'0000','msg'=>'添加成功');
		}
		return array('code'=>'-1001','msg'=>'因系统异常，添加失败');
	}
	
	/**
	 * 根据主键ID更新信息
	 * @param unknown $id
	 */
	public function updateInfoById($id, $update_data_info){
		$node_info = D("Usap/Authpuppy/Nodes")->where("id='$id'")->find();
		if(empty($node_info)){
			
			return array('code'=>'-1001','msg'=>'该设备不存在，无法更新');
		}

		if(empty($update_data_info)) return array('code'=>'-1002','msg'=>'更新信息为空，请重新填写');

		$data = array();
		if($update_data_info['province'] && $update_data_info['province']!=$node_info['province']) $data['province'] = $update_data_info['province'];
		if($update_data_info['city'] && $update_data_info['city']!=$node_info['city']) $data['city'] = $update_data_info['city'];
		if($update_data_info['district'] && $update_data_info['district']!=$node_info['country']) $data['country'] = $update_data_info['district'];

		if($update_data_info['street_name'] && $update_data_info['street_name']!=$node_info['street_name']) $data['street_name'] = $update_data_info['street_name'];
		if($update_data_info['station_no'] && $update_data_info['station_no']!=$node_info['station_no']) $data['station_no'] = $update_data_info['station_no'];
		if($update_data_info['mac_address'] && $update_data_info['mac_address']!=$node_info['mac_address']) $data['mac_address'] = $update_data_info['mac_address'];
		if($update_data_info['real_name'] && $update_data_info['real_name']!=$node_info['real_name']) $data['real_name'] = $update_data_info['real_name'];
		if($update_data_info['mobile'] && $update_data_info['mobile']!=$node_info['public_phone_number']) $data['public_phone_number'] = $update_data_info['mobile'];

		$deployment_status = 'TEMPORARILY_CLOSED';
		if($update_data_info['run_status']=='Run'){

			$deployment_status = 'DEPLOYED';
		}
		if($node_info['deployment_status']!=$deployment_status){
			
			$data['deployment_status'] = $deployment_status;
		}
		
		
		if(!empty($data['public_phone_number']) && !preg_match('/^1[0-9]{10}$/', $data['public_phone_number'])){

			return array('code'=>'MOBILE_ERROR','msg'=>'店主联系方式必须为11位数字');
		}
		
		if(!empty($data['mac_address']) && !preg_match('/^[0-9A-F]{12}$/', $data['mac_address'])){

			return array('code'=>'MACADDRESS_ERROR','msg'=>'您当前填写的网卡地址必须为12位字母与数字的混合串，且字母必须为大写');
		}
		
		if(!empty($data['mac_address'])){//MAC地址唯一
			
			$exists_no = D("Usap/Authpuppy/Nodes")->where("mac_address='".$data['mac_address']."'")->count();
			if($exists_no){

				return array('code'=>'-1004','msg'=>'相同MAC地址的设备之前已存在，请重试');
			}
		}
		
		if(!empty($data['station_no'])){//站点编号唯一
			
			$exists_no = D("Usap/Authpuppy/Nodes")->where("station_no='".$data['station_no']."'")->count();
			if($exists_no){
			
				return array('code'=>'-1005','msg'=>'相同站点编号的设备之前已存在，请重试');
			}
		}
		if($update_data_info['portal_page'] && $update_data_info['portal_page']!=$node_info['portal_page']){
			$data['portal_page'] = $update_data_info['portal_page'];
		}
		if($update_data_info['login_page'] && $update_data_info['login_page']!=$node_info['login_page']){
			$data['login_page'] = $update_data_info['login_page'];
		}
		$opt_result =  D("Usap/Authpuppy/Nodes")->where("id='$id'")->save($data);
		if($opt_result){

			return array('code'=>'0000','msg'=>'操作成功');
		}
		return array('code'=>'opt_fail','msg'=>'数据未做任何更新');
	}
	
	/**
	 * 根据主键ID获取信息
	 * @param unknown $id
	 * @return multitype:|unknown
	 */
	public function getInfoById($id){
		
		$node_info = D("Usap/Authpuppy/Nodes")->where("id='$id'")->find();
		if(empty($node_info)){
		
			return array();
		}
		
		if(in_array($node_info['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){
		
			$node_info['status'] = 'Stop';
		}else{
			if((time()-strtotime($node_info['updated_at']))<1800){
		
				$node_info['status'] = 'Run';
			}else{
				$node_info['status'] = 'Down';
			}
		}		
		$run_status_conf = Service::instance()->loadConfig('account', 'device', 'getRunStatusConf');
		$node_info['status_cn'] = $run_status_conf[$node_info['status']];
		return $node_info;
	}
	
	/**
	 * 根据站点编号获取信息列表
	 * @param string $station_no
	 */
	public function getListByStationNo($station_no){

		$node_info = D("Usap/Authpuppy/Nodes")->where("station_no='$station_no'")->find();
		if(empty($node_info)){

			return array();
		}

		$return_info = array();//返回值列表
		$return_info['id'] = $node_info['id'];//自增ID
		$return_info['gw_id'] = $node_info['gw_id'];//站点唯一标记
		$return_info['station_no'] = $node_info['station_no'];//站点编号
		$return_info['mobile'] = $node_info['public_phone_number'];//联系方式
		
		$return_info['mac_address'] = $node_info['mac_address'];//路由器MAC地址
		$return_info['ip_address'] = $node_info['mac_address'];//路由器IP地址
		
		
		$return_info['province'] = $node_info['province'];//省份
		$return_info['city'] = $node_info['city'];//城市
		$return_info['district'] = $node_info['district'];//地区
		$return_info['street_name'] = $node_info['street_name'];//街道详细地址
		
		$return_info['created_at'] = date('Y-m-d H:i:s',strtotime($node_info['created_at']));//注册时间
		$return_info['updated_at']  = date('Y-m-d H:i:s',strtotime($node_info['updated_at']));//最后一次更新时间
		
		//查询链接数
		$return_info['connection_no'] = $connection_no  = $this->getValidateConnectionNo($node_info['id']);

		
		
		
		
		$online_node_no = $downline_node_no = $shutdownline_node_no = 0;
		if(in_array($node_info['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){
				
			$return_info['status'] = 'Stop';
			$shutdownline_node_no = 1;
		}else{
			if((time()-strtotime($node_info['updated_at']))<1800){
		
				$return_info['status'] = 'Run';
				$online_node_no = 1;
			}else{
				$return_info['status'] = 'Down';
				$downline_node_no = 0;
			}
		}
		$run_status_conf = Service::instance()->loadConfig('account', 'device', 'getRunStatusConf');
		$return_info['status_cn'] = $run_status_conf[$return_info['status']];
		return array(
				'sum_node_no'=>1,
				'online_node_no'=>$online_node_no,
				'downline_node_no'=>$downline_node_no,
				'shutdownline_node_no'=>$shutdownline_node_no,
				'connection_no'=>$connection_no,
				'count'=>1,
				'list'=>array($return_info),
		);
	}
	
	
	/**
	 * 根据网卡地址获取信息列表
	 * @param string $mac_address
	 */
	public function getListByMacAddress($mac_address){
		
		
		$node_info = D("Usap/Authpuppy/Nodes")->where("mac_address='$mac_address'")->find();
		if(empty($node_info)){
		
			return array();
		}
		
		
		$return_info = array();//返回值列表
		$return_info['id'] = $node_info['id'];//自增ID
		$return_info['gw_id'] = $node_info['gw_id'];//站点唯一标记
		$return_info['station_no'] = $node_info['station_no'];//站点编号
		$return_info['mobile'] = $node_info['public_phone_number'];//联系方式
		
		$return_info['mac_address'] = $node_info['mac_address'];//路由器MAC地址
		$return_info['ip_address'] = $node_info['mac_address'];//路由器IP地址
		
		
		
		$return_info['province'] = $node_info['province'];//省份
		$return_info['city'] = $node_info['city'];//城市
		$return_info['district'] = $node_info['district'];//地区
		$return_info['street_name'] = $node_info['street_name'];//街道详细地址
		
		$return_info['created_at'] = $node_info['created_at'];//注册时间
		$return_info['updated_at']  = $node_info['updated_at'];//最后一次更新时间
		
		//查询链接数
		$return_info['connection_no'] = $connection_no = $this->getValidateConnectionNo($node_info['id']);

		$online_node_no = $downline_node_no = $shutdownline_node_no = 0;
		if(in_array($node_info['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){
		
			$return_info['status'] = 'Stop';
			$shutdownline_node_no = 1;
		}else{
			if((time()-strtotime($node_info['updated_at']))<1800){
		
				$return_info['status'] = 'Run';
				$online_node_no = 1;
			}else{
				$return_info['status'] = 'Down';
				$downline_node_no = 0;
			}
		}
		$run_status_conf = Service::instance()->loadConfig('account', 'device', 'getRunStatusConf');
		$return_info['status_cn'] = $run_status_conf[$result_info['status']];
		
		
		return array(
				'sum_node_no'=>1,
				'online_node_no'=>$online_node_no,
				'downline_node_no'=>$downline_node_no,
				'shutdownline_node_no'=>$shutdownline_node_no,
				'connection_no'=>$connection_no,
				'count'=>1,'list'=>array($return_info),
		);
		
		return $return_info;
	}
	
	
	/**
	 * 根据ip地址获取信息列表
	 * @param string $ip_address
	 */
	public function getListByIpAddress($ip_address,$page=-1, $page_size=20){
		
		$count = D("Usap/Authpuppy/Nodes")->where("ip_address='$ip_address'")->count();
		if(empty($count)){
		
			return array();
		}
		

		$limit = '';
		if($page_size > 0){
		
			$page_start = intval($page-1) * $page_size;
		
			$limit = $page_start . "," . $page_size;
			$node_list = D("Usap/Authpuppy/Nodes")->where("ip_address='$ip_address'")->order("id desc")->limit($limit)->select();
		}else{
			$node_list = D("Usap/Authpuppy/Nodes")->where("ip_address='$ip_address'")->order("id desc")->select();
		}
		

		$return_info = array();
		$online_node_no = $downline_node_no = $shutdownline_node_no = $connection_no = 0;
		foreach($node_list as $node_key=>$node_info){
			
			$return_info[$node_key]['id'] = $node_info['id'];//自增ID
			$return_info[$node_key]['gw_id'] = $node_info['gw_id'];//站点唯一标记
			$return_info[$node_key]['station_no'] = $node_info['station_no'];//站点编号
			$return_info[$node_key]['mobile'] = $node_info['public_phone_number'];//联系方式
			$return_info[$node_key]['mac_address'] = $node_info['mac_address'];//路由器MAC地址
			$return_info[$node_key]['ip_address'] = $node_info['mac_address'];//路由器IP地址
			
			
			$return_info[$node_key]['province'] = $node_info['province'];//省份
			$return_info[$node_key]['city'] = $node_info['city'];//城市
			$return_info[$node_key]['district'] = $node_info['district'];//地区
			$return_info[$node_key]['street_name'] = $node_info['street_name'];//街道详细地址
			
			$return_info[$node_key]['created_at'] = $node_info['created_at'];//注册时间
			$return_info[$node_key]['updated_at']  = $node_info['updated_at'];//最后一次更新时间


			//查询链接数
			$return_info[$node_key]['connection_no'] = $this->getValidateConnectionNo($node_info['id']);
			
			if(in_array($node_info['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){
					
				$return_info[$node_key]['status'] = 'Stop';
				$downline_node_no++;
			}else{
				if((time()-strtotime($node_info['updated_at']))<1800){
			
					$return_info[$node_key]['status'] = 'Run';
					$online_node_no++;
				}else{
					$return_info[$node_key]['status'] = 'Down';
					$downline_node_no++;
				}
			}
			$return_info[$node_key]['status_cn'] = $run_status_conf[$node_info['status']];
			$connection_no += $return_info[$node_key]['connection_no'];
		}
		
		
		return array(
				'sum_node_no'=>1,
				'online_node_no'=>$online_node_no,
				'downline_node_no'=>$downline_node_no,
				'shutdownline_node_no'=>$shutdownline_node_no,
				'connection_no'=>$connection_no,
				'count'=>$count,'list'=>$return_info,
		);
	}
	
	
	/**
	 *  根据网关ID查询列表信息
	 * @param unknown $gw_id
	 * @param unknown $page
	 * @param number $page_size
	 */
	public function getListByGwId($gw_id,$page=-1, $page_size=20){
		
		$node_info = D("Usap/Authpuppy/Nodes")->where("gw_id='$gw_id'")->find();
		if(empty($node_info)){
		
			return array();
		}
		
		
		$return_info = array();//返回值列表
		$return_info['id'] = $node_info['id'];//自增ID
		$return_info['gw_id'] = $node_info['gw_id'];//站点唯一标记
		$return_info['station_no'] = $node_info['station_no'];//站点编号
		$return_info['mobile'] = $node_info['public_phone_number'];//联系方式
		
		$return_info['mac_address'] = $node_info['mac_address'];//路由器MAC地址
		$return_info['ip_address'] = $node_info['mac_address'];//路由器IP地址
		
		
		
		$return_info['province'] = $node_info['province'];//省份
		$return_info['city'] = $node_info['city'];//城市
		$return_info['district'] = $node_info['district'];//地区
		$return_info['street_name'] = $node_info['street_name'];//街道详细地址
		
		$return_info['created_at'] = $node_info['created_at'];//注册时间
		$return_info['updated_at']  = $node_info['updated_at'];//最后一次更新时间
		
		//查询链接数
		$return_info['connection_no'] = $connection_no = $this->getValidateConnectionNo($node_info['id']);
		
		$online_node_no = $downline_node_no = $shutdownline_node_no = 0;
		if(in_array($node_info['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){

			$return_info['status'] = 'Stop';
			$shutdownline_node_no = 1;
		}else{
			if((time()-strtotime($node_info['updated_at']))<1800){
		
				$return_info['status'] = 'Run';
				$online_node_no = 1;
			}else{
				$return_info['status'] = 'Down';
				$downline_node_no = 0;
			}
		}
		$run_status_conf = Service::instance()->loadConfig('account', 'device', 'getRunStatusConf');
		$return_info['status_cn'] = $run_status_conf[$result_info['status']];
		
		return array(
				'sum_node_no'=>1,
				'online_node_no'=>$online_node_no,
				'downline_node_no'=>$downline_node_no,
				'shutdownline_node_no'=>$shutdownline_node_no,
				'connection_no'=>$connection_no,
				'count'=>1,'list'=>array($return_info),
		);
		
		return $return_info;
	}
	
	/**
	 * 根据连接ID获取连接数
	 * @param unknown $node_id
	 */
	public function getValidateConnectionNo($node_id){
		
		$count =  D("Usap/Authpuppy/Connections")->where("node_id='$node_id' AND `status`='TOKEN_VALIDATED'")->count();
		return $count>0 ? $count : 0;
	}
	
	/**
	 * 通过信息获取信息列表
	 * @param string $province
	 * @param string $city
	 * @param string $district
	 * @param string $run_status
	 * @param unknown $page
	 * @param number $page_size
	 */
	public function getList($province='', $city='', $district='', $run_status='',$page=-1, $page_size=20){

		$where = " 1 AND 1 ";
		if($province) $where .= " AND province='$province' ";
		
		if($city) $where .= " AND city='$city' ";
		
		if($district) $where .= " AND country='$district' ";
		
		if($run_status){
			
			if($run_status=='Stop'){

				$where .= " AND deployment_status IN ('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED') ";
			}else{
				if($run_status=='Run'){
					
					$half_hour = date('Y-m-d H:i:s',(time()-1800));//半小时内定为运行中
					$where .= " AND updated_at>='$half_hour'";
				}			
			}
		}
		$node_count = D("Usap/Authpuppy/Nodes")->where($where)->count();
		if(empty($node_count)){
			
			return array('count'=>$node_count,'list'=>array());
		}

		$limit = '';
		if($page_size != -1){
		
			$page_start = intval($page-1) * $page_size;
		
			$limit = $page_start . "," . $page_size;
		}
		
		$connection_no = 0;//链接数
		$online_node_no = 0;//在线台数
		$downline_node_no = 0;//离线台数
		$shutdownline_node_no = 0;//停机台数
		
		$sum_node_no  = D("Usap/Authpuppy/Nodes")->where($where)->count();//设备总台数
		$result_list = D("Usap/Authpuppy/Nodes")->where($where)->order("updated_at desc")->limit($limit)->select();
		
		//汇总统计数
		$stat_list = D("Usap/Authpuppy/Nodes")->where($where)->select();
		if($stat_list){

			foreach ($stat_list as $k=>$v){

				if(in_array($v['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){
					
					$shutdownline_node_no++;
				}else{
					if((time()-strtotime($v['updated_at']))<1800){
					
						$online_node_no++;
					}else{
						$downline_node_no++;
					}
				}
				$connection_no += $this->getValidateConnectionNo($v['id']);
			}
		}
		
		
		$run_status_conf = Service::instance()->loadConfig('account', 'device', 'getRunStatusConf');
		foreach($result_list as &$result_info){
			
			$result_info['connection_no'] = $this->getValidateConnectionNo($result_info['id']);
			
			if(in_array($result_info['deployment_status'],array('TEMPORARILY_CLOSED','PERMANENTLY_CLOSED'))){
			
				$result_info['status'] = 'Stop';
			}else{
				if((time()-strtotime($result_info['updated_at']))<1800){

					$result_info['status'] = 'Run';
				}else{
					$result_info['status'] = 'Down';
				}
			}
			$result_info['status_cn'] = $run_status_conf[$result_info['status']];
		}
		return array(
				'sum_node_no'=>$sum_node_no,
				'online_node_no'=>$online_node_no,
				'downline_node_no'=>$downline_node_no,
				'shutdownline_node_no'=>$shutdownline_node_no,
				'connection_no'=>$connection_no,
				'count'=>$node_count,'list'=>$result_list,
		);
	}
	
}


